namespace SimpleWebServices.Web.UI.Html
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Xml;
    using System.Xml.Serialization;

    [XmlRoot("button")]
    public abstract class Button : Control, IAttributeAccesskey, IXmlSerializable
    {
        protected Button()
        {
        }

        protected Button(Name id)
            : base(id)
        {
        }

        public char? Accesskey
        {
            get;
            set;
        }

        [SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods", Justification = "The naming is intentionally the same as HTML.")]
        public abstract string Type { get; }

        public override string Value
        {
            get;
            set;
        }

        public override void ReadXml(XmlReader reader)
        {
            base.ReadXml(reader);

            if (!this.Type.Equals(reader.GetAttribute("type"), StringComparison.OrdinalIgnoreCase))
            {
                throw new XmlException("The input is of an unexpected type.");
            }

            string value = reader.GetAttribute("accesskey");
            if (!string.IsNullOrEmpty(value))
            {
                this.Accesskey = value[0];
            }

            this.Value = reader.GetAttribute("value");
        }

        public override void WriteXml(XmlWriter writer)
        {
            base.WriteXml(writer);

            if (this.Accesskey.HasValue)
            {
                writer.WriteAttributeString("accesskey", this.Accesskey.Value.ToString());
            }

            writer.WriteAttributeString("type", this.Type);
            writer.WriteAttributeString("value", this.Value);
        }
    }
}